//initData.js
export const state = () => ({
  deviceType: '', // 设备类型
  initData: {}, // 初始化数据
  userSelect: {}, // 用户选择的数据(国家/货币/语言等)
  goodsCategory: [], // 商品分类数据
  curPath: {}, // 当前路径信息
  regions: [], // 地区数据
  currencies: {}, // 货币数据
  language: {}, // 语言数据
  footer: {} // 页脚数据
})
export const mutations = {
  // 更新通用key值，用于强制组件刷新
  setKey(state, data) {
    state.key = data
  },
  // 设置页脚数据
  setFooter(state, data) {
    state.footer = data
  },
  // 设置设备类型并保存到cookies中
  setDeviceType(state, data) {
    state.deviceType = data
    // if (process.client) {
    //   this.$cookies.set("deviceType", data);
    // }
  },
  // 设置当前路径信息并保存到localStorage中
  setCurPath(state, data) {
    state.curPath = data || {}
    if (process.client) {
      localStorage.setItem('curPath', JSON.stringify(data))
    }
  },
  // 设置初始化数据
  setInitData(state, data) {
    state.initData = data || {}
  },
  // 设置地区、货币和语言数据
  setInitData2(state, data) {
    state.regions = data.regions || []
    state.currencies = data.currencies || {}
    state.language = data.language || {}
  },
  // 设置商品分类数据
  setCategoryData(state, data) {
    state.goodsCategory = data || []
  },
  // 默认初始化用户选中翻译数据
  initUserSelect(state, data) {
    const userSelect = this.$cookies.get('userSelect') || {}
    const defaultSelect = {
      country_icon: userSelect.country_icon || '/flag/United%20States.png',
      country_code: userSelect.country_code || 'US',
      currency_code: userSelect.currency_code || 'USD',
      language_code: data || this.$cookies.get('i18n_redirected')
    }
    this.$cookies.set('userSelect', defaultSelect)
  }
}
export const actions = {
  // 获取页脚数据
  async getFooterData({ commit }) {
    try {
      const res = await this.$axios.get('/api/common/footer')
      if (res) {
        // 为 footer_link 中的每一项添加 isOpen 字段
        if (res.footer_link && Array.isArray(res.footer_link)) {
          res.footer_link = res.footer_link.map(item => ({
            ...item,
            isOpen: false
          }))
        }
        commit('setFooter', res || {})
      }
    } catch (error) {
      console.error('获取页脚数据失败:', error)
    }
  },
  // 获取初始化数据
  async getInitData({ commit, rootState }) {
    try {
      // 生成32位UUID
      const generateUUID = () => {
        // 获取当前时间戳
        const timestamp = Date.now()
        const key = Math.floor(Math.random() * 1000000)
        const obfuscatedTimestamp = (timestamp ^ key).toString(36)
        const uuid = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
          const r = (Math.random() * 16) | 0
          const v = c === 'x' ? r : (r & 0x3) | 0x8
          return v.toString(16)
        })
        const combined = `${obfuscatedTimestamp}${uuid}`.slice(0, 36)
        return combined
      }

      let uuid = this.$cookies.get('uuid')

      if (!uuid) {
        uuid = generateUUID()
        this.$cookies.set('uuid', uuid)
      }
      const res = await this.$axios.get(`/api/common/init?version=1.2.1&lng=&lat=&vt=${uuid}`)
      if (res) commit('setInitData', res)
    } catch (error) {
      console.error('获取初始化数据失败:', error)
    }
  },
  // 获取多语言数据
  async getInitData2({ commit }) {
    try {
      const res = await this.$axios.get(`/api/index/regions`)
      if (res) commit('setInitData2', res)
    } catch (error) {
      console.error('获取多语言数据失败:', error)
    }
  },
  // 获取分类数据
  async getCategoryData({ commit }) {
    try {
      const res = await this.$axios.get(`/api/goods_category/index`)
      // 为每个分类项添加 show 字段
      const processedData = Array.isArray(res)
        ? res.map(item => ({
            ...item,
            isOpen: false,
            isOpenH5: false,
            lang: this.$i18n.locale
          }))
        : []
      commit('setCategoryData', processedData)
    } catch (error) {
      console.error('获取分类数据失败:', error)
    }
  }
}
export const getters = {}
